package org.hxzon.tapestry5.components;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.project.SplitPageInfo;

public class SplitPageBar {

    @Property
    @Parameter(required = true, principal = true)
    private SplitPageInfo pageInfo;

    @Inject
    private ComponentResources resources;

    @BeginRender
    void begin(MarkupWriter writer) {
        Link link = resources.createEventLink("test");
        String basePath = link.getBasePath();
        String pageParameter = link.getParameterValue("t:ac");
        basePath = basePath.substring(0, basePath.indexOf('.'));
        pageParameter = pageParameter.substring(0, pageParameter.lastIndexOf('/'));
        String prefix = basePath + "/" + pageParameter;
        //
        long currentPage = pageInfo.getCurrentPage();
        long pageCount = pageInfo.getPageCount();
        long start = currentPage - 4;
        if (start < 2) {
            start = 2;
        }
        long end = start + 8;
        if (end > pageCount) {
            end = pageCount;
            long reStart = end - 8;
            if (reStart > 2) {
                start = reStart;
            } else {
                start = 2;
            }
        }
        writer.element("div", "class", "splitPageBar");
        writePage(writer, 1, 1 == currentPage, prefix);
        for (long i = start; i < end; i++) {
            writePage(writer, i, i == currentPage, prefix);
        }
        writePage(writer, pageCount, pageCount == currentPage, prefix);
        long tmp = currentPage - 1;
        writePage(writer, "上一页", tmp, tmp > 0, prefix);
        tmp = currentPage + 1;
        writePage(writer, "下一页", tmp, tmp <= pageCount, prefix);
        writer.end();//div
    }

    private void writePage(MarkupWriter writer, long page, boolean currentPage, String prefix) {
        if (currentPage) {
            writer.element("span", "class", "cur");
        } else {
            writer.element("a", "href", prefix + "/" + page);
        }
        writer.write("第" + page + "页");
        writer.end();
    }

    private void writePage(MarkupWriter writer, String text, long page, boolean available, String prefix) {
        if (available) {
            writer.element("a", "href", prefix + "/" + page);
        } else {
            writer.element("span");
        }
        writer.write(text);
        writer.end();
    }

}
